package com.likeyoudo.views.fragment.public_service;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.likeyoudo.common.BaseFragment;
import com.likeyoudo.common.constant.QueryParamsKey;
import com.likeyoudo.common.msg.MsgEvent;
import com.likeyoudo.common.utils.CommonUtils;
import com.likeyoudo.common.widget.recycleview.interfaces.OnLoadMoreListener;
import com.likeyoudo.common.widget.recycleview.interfaces.OnNetWorkErrorListener;
import com.likeyoudo.common.widget.recycleview.interfaces.OnRefreshListener;
import com.likeyoudo.common.widget.recycleview.recyclerview.LRecyclerView;
import com.likeyoudo.common.widget.recycleview.recyclerview.LRecyclerViewAdapter;
import com.likeyoudo.common.widget.spinner.NiceSpinner;
import com.likeyoudo.common.widget.spinner.NiceSpinnerItem;
import com.likeyoudo.common.widget.spinner.OnSpinnerItemSelectedListener;
import com.likeyoudo.views.R;
import com.likeyoudo.views.adapter.rv.ApprovalRvAdapter;
import com.likeyoudo.views.api.system.DictApi;
import com.likeyoudo.views.api.xg.ApprovalApi;
import com.likeyoudo.views.databinding.FragmentPublicServiceApprovalBinding;
import com.likeyoudo.views.type.entity.Dict;
import com.likeyoudo.views.type.entity.xg.Approval;
import com.likeyoudo.views.type.response.PageResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

/**
 * @author LikeYouDo
 * @date 2023/12/28 11:28
 */
public class ApprovalFragment extends BaseFragment {
    @Override
    public int getLayoutId() {
        return R.layout.fragment_public_service_approval;
    }

    private LRecyclerView rvApproval;
    private boolean isLoading = true;
    private boolean isLoadMore = false;
    // private boolean isRefresh = false;
    private int total = 0;
    private int pageNum = 1;
    private final int pageSize = 5;

    private Map<String, String> queryParams = MapUtil.<String, String>builder().put(QueryParamsKey.PAGE_NUM, String.valueOf(pageNum)).put(QueryParamsKey.PAGE_SIZE, String.valueOf(pageSize)).build();
    private ApprovalApi approvalApi;
    private final LRecyclerViewAdapter approvalRvAdapter = new LRecyclerViewAdapter(new ApprovalRvAdapter(null));
    private DictApi dictApi;
    private FragmentPublicServiceApprovalBinding binding;
    private ArrayList<NiceSpinnerItem> stateItems;
    private ArrayList<NiceSpinnerItem> yearItems;

    private final String XG_APPROVAL_STATE = "xg_approve_state";
    private final String XG_APPLICATION_YEAR = "xg_application_year";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentPublicServiceApprovalBinding.inflate(inflater, container, false);
        EventBus.getDefault().register(this);
        initView();

        return binding.getRoot();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        // 请求字典数据
        dictApi = new DictApi();
        approvalApi = new ApprovalApi();
        dictApi.getDicts(XG_APPROVAL_STATE);
        dictApi.getDicts(XG_APPLICATION_YEAR);
    }

    private void initView() {
        rvApproval = binding.approvalRv;
        rvApproval.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvApproval.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 取消焦点
                CommonUtils.clearFocus(getActivity());
                ((ApprovalRvAdapter) approvalRvAdapter.getInnerAdapter()).getList().clear();
                approvalRvAdapter.notifyDataSetChanged();
                pageNum = 1;
                queryParams.put(QueryParamsKey.PAGE_NUM, String.valueOf(pageNum));
                // isRefresh = true;
                approvalApi.list(queryParams);
            }
        });
        rvApproval.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                // 向上取整
                int totalPage = total / pageSize + 1;
                if (pageNum < totalPage) {
                    pageNum++;
                    queryParams.put(QueryParamsKey.PAGE_NUM, String.valueOf(pageNum));
                    approvalApi.list(queryParams);
                    isLoadMore = true;
                } else {
                    rvApproval.setNoMore(true);
                }
            }
        });
        rvApproval.setOnNetWorkErrorListener(new OnNetWorkErrorListener() {
            @Override
            public void reload() {
                approvalApi.list(queryParams);
            }
        });

        // 监听搜索触发事件
        binding.searchView2.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                queryParams.put("nickName", s);
                pageNum = 1;
                // 刷新
                rvApproval.forceToRefresh();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }
        });

        // 关闭后清空搜索项
        binding.searchView2.setOnCloseListener(new SearchView.OnCloseListener() {

            @Override
            public boolean onClose() {
                queryParams.remove("nickName");
                pageNum = 1;
                // 刷新
                rvApproval.forceToRefresh();
                return false;
            }
        });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MsgEvent event) {
        String type = event.getType();
        if (approvalApi.listMsgType().equals(type)) {
            // 设置total值
            total = event.getResponse(PageResponse.class).getTotal();
            // 更新列表
            List<Approval> listData = event.getListData(Approval.class);
            ApprovalRvAdapter innerAdapter = (ApprovalRvAdapter) approvalRvAdapter.getInnerAdapter();

            if (isLoadMore) {
                innerAdapter.getList().addAll(listData);
                rvApproval.refreshComplete(pageSize);
                isLoadMore = false;
                isLoading = false;
            }

            if (innerAdapter.getList() == null || innerAdapter.getList().size() == 0) {
                innerAdapter.setList(listData);
                rvApproval.setAdapter(approvalRvAdapter);
                rvApproval.refreshComplete(pageSize);
            }

        } else if (dictApi.getMsgType().equals(type)) {
            List<Dict> listData = event.getListData(Dict.class);
            // 设置数据

            if (listData != null && listData.size() > 0) {
                Dict dict = listData.get(0);
                // 设置页数为第一页
                queryParams.put(QueryParamsKey.PAGE_NUM, "1");
                switch (dict.getDictType()) {
                    case XG_APPROVAL_STATE:
                        stateItems = new ArrayList<>();
                        // 审批状态
                        stateItems.add(new NiceSpinnerItem("全部", null));
                        for (Dict listDatum : listData) {
                            stateItems.add(new NiceSpinnerItem(listDatum.getDictLabel(), listDatum.getDictValue()));
                        }
                        binding.menuApprovalState.attachDataSource(stateItems);
                        // 设置点击事件
                        binding.menuApprovalState.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
                            @Override
                            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                                // 点击后发送查询请求
                                NiceSpinnerItem item = (NiceSpinnerItem) parent.getItemAtPosition(position);
                                queryParams.put("state", item.getValue());
                                // 强制刷新
                                rvApproval.forceToRefresh();
                                approvalApi.list(queryParams);
                            }
                        });
                        break;
                    case XG_APPLICATION_YEAR:
                        // 申请年份
                        Dict dict1 = listData.get(0);
                        if (dict1 != null) {
                            if (StrUtil.isBlank(queryParams.get(XG_APPLICATION_YEAR))) {
                                // 初始化请求参数
                                queryParams.put("approvalYear", dict1.getDictValue());
                            }
                            int dictValue = Integer.parseInt(dict1.getDictValue());
                            yearItems = new ArrayList<>();
                            for (int i = 0; i < 5; i++) {
                                yearItems.add(new NiceSpinnerItem((dictValue - i) + "年度", (dictValue - i) + ""));
                            }
                            binding.menuApplicationYear.attachDataSource(yearItems);
                            // 设置点击事件
                            binding.menuApplicationYear.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
                                @Override
                                public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                                    // 点击后发送查询请求
                                    NiceSpinnerItem item = (NiceSpinnerItem) parent.getItemAtPosition(position);
                                    queryParams.put("approvalYear", item.getValue());
                                    // 强制刷新
                                    rvApproval.forceToRefresh();
                                    approvalApi.list(queryParams);
                                }
                            });
                        } else {
                            binding.menuApplicationYear.setVisibility(View.GONE);
                            ToastUtils.showLong("管理员未设置当前申请年度");
                        }
                        approvalApi.list(queryParams);
                        break;
                }
            }
        }else if(approvalApi.updateMsgType().equals(type)){
            // 强制刷新
            rvApproval.forceToRefresh();
            approvalApi.list(queryParams);
        }
    }
}